﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Ttifa.WebApiBase
{
    public class ApiResult
    {
        /// <summary>
        /// 消息
        /// </summary>
        [JsonProperty("msg")]
        public string Message { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        [JsonProperty("status")]
        public ApiStatus Status { get; set; }
        /// <summary>
        /// 是否成功(此属性忽略序列化)
        /// </summary>
        [JsonIgnore]
        public bool OK => this.Status == ApiStatus.OK;
        /// <summary>
        /// 数据
        /// </summary>
        [JsonProperty("data")]
        public object Data { get; set; }
        /// <summary>
        /// 分页信息
        /// </summary>
        [JsonProperty("page")]
        public ApiResultPage Page { get; set; }

        public ApiResult(ApiStatus status = ApiStatus.OK, string message = null, object data = null, ApiResultPage page = null)
        {
            this.Status = status;
            this.Message = message;
            this.Data = data;
            this.Page = page;
        }

        #region "创建同步响应消息"

        /// <summary>
        /// 创建同步响应消息
        /// </summary>
        /// <param name="result">消息内容</param>
        /// <returns></returns>
        public static HttpResponseMessage Response(ApiResult result)
            => Response(result.Status, result.Message, result.Data, result.Page);

        /// <summary>
        /// 创建同步响应消息
        /// </summary>
        /// <param name="module">模块标识（只取两位字符，不足两位在前面补0）</param>
        /// <param name="status">状态标识</param>
        /// <param name="message">消息</param>
        /// <param name="data">数据/数据对象</param>
        /// <param name="page">分页信息</param>
        /// <returns></returns>
        public static HttpResponseMessage Response(ApiStatus status, string message = null, object data = null, ApiResultPage page = null)
        {
            var result = new ApiResult(status, message, data, page);
            var json = new StringBuilder(JsonConvert.SerializeObject(result));

            if (HttpContext.Current.Request.HttpMethod == "GET" && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["jsonp"]))
            {
                json.Insert(0, HttpContext.Current.Request.QueryString["jsonp"] + "(").Append(");");
            }

            return new HttpResponseMessage()
            {
                Content = new StringContent(json.ToString(), Encoding.UTF8, "application/json")
            };
        }

        #endregion

        #region "创建异步响应消息"

        /// <summary>
        /// 创建异步响应消息
        /// </summary>
        /// <param name="result">消息内容</param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> TaskResponse(ApiResult result)
            => Task.FromResult<HttpResponseMessage>(Response(result));

        /// <summary>
        /// 创建异步响应消息
        /// </summary>
        /// <param name="module">模块标识（只取两位字符，不足两位在前面补0）</param>
        /// <param name="status">状态标识</param>
        /// <param name="message">消息</param>
        /// <param name="data">数据/数据对象</param>
        /// <param name="page">分页信息</param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> TaskResponse(ApiStatus status, string message = null, object data = null, ApiResultPage page = null)
            => Task.FromResult<HttpResponseMessage>(Response(status, message, data, page));

        #endregion
    }

    public class ApiResult<T> : ApiResult
    {
        /// <summary>
        /// 数据
        /// </summary>
        [JsonProperty("data")]
        public new T Data { get; set; }

        public ApiResult(ApiStatus status = ApiStatus.OK, string message = null, T data = default(T), ApiResultPage page = null)
        {
            this.Status = status;
            this.Message = message;
            this.Data = data;
            this.Page = page;
        }
    }

    /// <summary>
    /// 分页信息
    /// </summary>
    public class ApiResultPage
    {
        /// <summary>
        /// 初始化分页信息
        /// </summary>
        /// <param name="index">当前页码：默认1</param>
        /// <param name="size">页面大小：默认10</param>
        public ApiResultPage(int index = 1, int size = 10)
        {
            this.Index = index;
            this.Size = size;
        }

        /// <summary>
        /// 当前页
        /// </summary>
        [JsonProperty("index")]
        public int Index;

        /// <summary>
        /// 每一页大小
        /// </summary>
        [JsonProperty("size")]
        public int Size;

        /// <summary>
        /// 总页数
        /// </summary>
        [JsonProperty("count")]
        public int PageCount;

        /// <summary>
        /// 总数量
        /// </summary>
        [JsonProperty("total")]
        public int Total;
    }

    public enum ApiStatus
    {
        /// <summary>
        /// 非法请求
        /// </summary>
        Illegal = -2,
        /// <summary>
        /// 失败
        /// </summary>
        Fail = -1,
        /// <summary>
        /// 成功
        /// </summary>
        OK = 1,
        /// <summary>
        /// 未登录
        /// </summary>
        NoLogin,
        /// <summary>
        /// 参数异常
        /// </summary>
        ParamError,
        /// <summary>
        /// 交易失败（见证宝ERR020）
        /// </summary>
        TradeFail,
        /// <summary>
        /// 订单已付款
        /// </summary>
        HadPaid = 100,
        NotFound = 404,
        BadRequest = 500
    }
}